package com.lecture.java8.gui;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Service {
    public static ArrayList<User> getTime(String sql) {//获取数据
        Connection conn = null;
        Statement stmt = null;
        ArrayList<User> userList=new ArrayList<User>();
        ArrayList<User> rsList=new ArrayList<User>();
        try {
            conn = getConnection.getConnection();
            //数据库编写sql语句
            stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            List<String> dataList = new ArrayList<>();
            List<Integer> dateList=new ArrayList<>();


            //解析结果集
            while(rs.next()){
                int current=rs.getInt("date");
                String data = rs.getString("starting");
                dateList.add(current);
                if (data.substring(1,2).equals(":")){
                    data="0"+data;
                }
                dataList.add(data);
                userList.add(new User(rs.getInt("date"), rs.getInt("id"),rs.getString("name"), rs.getString("starting"),rs.getInt("lasting")));
            }


            Collections.sort(dateList);
            Collections.sort(dataList);
            rsList=sortingDate(userList, (ArrayList<Integer>) dateList,rsList);



            for (int k=0;k<dataList.size();k++){
                if (dataList.get(k).substring(0,1).equals("0")){
                    dataList.set(k,dataList.get(k).substring(1));
                }
            }



            System.out.println("————sql已经执行!");
            System.out.println("————数据已更新!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("出现异常:" + e);
        } finally {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return rsList;
    }
    public static boolean setTime(String sql) {//设置数据
        Connection conn = null;
        Statement stmt = null;
        boolean msg=false;
        try {
            conn = getConnection.getConnection();
            //数据库编写sql语句

            stmt = conn.createStatement();
            int rs=stmt.executeUpdate(sql);

            if (rs>0){
                msg=true;
            }
            System.out.println("————sql已经执行!");
            System.out.println("————数据已更新!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("DAO出现异常:" + e);
        } finally {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return msg;
    }
    public static ArrayList<User> sortingDate(ArrayList<User> userList, ArrayList<Integer> dateList, ArrayList<User> rsList){
        while (dateList.size()!=0){
            int a=dateList.get(0);
            for (int j=0;j<userList.size();j++){
                User b=userList.get(j);
                if (b.getDate()==a){
                    rsList.add(b);
                    userList.remove(j);
                }
            }
            int m=dateList.remove(0);
        }
        int size=dateList.size();
        for (int n = 1; n < size; n++) {
            User u=rsList.get(n);
            String insert=u.getStarting();
            int current=n;

            while (u.getDate()==rsList.get(current-1).getDate() && current>0 && insert.compareTo(rsList.get(current-1).getStarting())<0){
                rsList.set(current,rsList.get(current-1));
                current--;
            }
            if (current!=n){
                rsList.set(current,u);
            }
        }
        return rsList;
    }
    public ArrayList<User> showAllTime(){
        String sql="select * from timetable;";
        ArrayList<User> userList=getTime(sql);
        ArrayList<User> rsList=new ArrayList<User>();
        System.out.println("——————————All Time Listed—————————");
        for (User u:userList){
            int hour,min,endMin,endHour;
            if (u.getStarting().substring(1,2).equals(":")){
                hour=Integer.valueOf(u.getStarting().substring(0,1));
                min=Integer.valueOf(u.getStarting().substring(2));
            }
            else{
                hour=Integer.valueOf(u.getStarting().substring(0,2));
                min=Integer.valueOf(u.getStarting().substring(3));
            }
            int temp=min+u.getLasting();
            if (temp>=60){
                endMin=temp-60;
                endHour=hour+1;
            }
            else{
                endMin=temp;
                endHour=hour;
            }
            String formattedNum;
            if(endMin/10==0) {
                formattedNum = String.format("%02d", endMin);
            }
            else{
                formattedNum=String.valueOf(endMin);
            }
            System.out.println("date："+u.getDate()+"  "+"id："+u.getId()+"  "+"name："+u.getName()+"  "+"starting："+u.getStarting()+"  "+"ending："+endHour+":"+formattedNum);
        }

        System.out.println("——————————————————————————————————");
        return userList;
    }
    public static User showOneTime(int id){
        String sql="select * from `timetable` where `id`="+id+";";
        ArrayList<User> userList = getTime(sql);
        User u = new User();
        if (userList != null && !userList.isEmpty()) {
            u = userList.get(0);
        }
        return u;
    }
    public static void addition(){
        Scanner s = new Scanner(System.in);
        System.out.println("请输入想要制定计划的日期：");
        int date = s.nextInt();
        System.out.println("请输入活动的名字:");
        String name = s.next();
        System.out.println("请输入活动的开始时间：");
        String starting=s.next();
        System.out.println("请输入活动的持续时间（分钟）:");
        int lasting=s.nextInt();
        String sql = "insert into timetable (`date`,`name`,`starting`,`lasting`) values ("+date+",'"+name+"','"+starting+"','"+lasting+"');";
        boolean result=setTime(sql);
        if (result){
            System.out.println("添加成功!请问您还需要继续添加任务吗？(yes or no)");
            String rs=s.next();
            if (rs.equals("yes")){
                addition();
            }
        }
        else{
            System.out.println("添加失败！");
        }


    }

    public static boolean deletion(int id){
        String sql="delete from timetable where id="+id+";";
        boolean result=setTime(sql);
        return result;
    }

    public static void alterStarting(){
        Scanner s = new Scanner(System.in);
        System.out.println("请输入想要修改的活动id:");
        int id = s.nextInt();
        System.out.println("请输入修改后的开始时间：");
        String starting=s.next();
        String sql="update `timetable` set `starting`= '"+starting+"' where `id`= "+id+";";
        boolean result=setTime(sql);
        if (result){
            System.out.println("修改成功！");
        }
        else{
            System.out.println("修改失败！");
        }
    }
    public static void alterLasting(){
        Scanner s = new Scanner(System.in);
        System.out.println("请输入想要修改的活动id:");
        int id = s.nextInt();
        System.out.println("请输入修改后的活动时长：");
        int lasting=s.nextInt();
        String sql="update `timetable` set `lasting`= '"+lasting+"' where `id`= "+id+";";
        boolean result=setTime(sql);
        if (result){
            System.out.println("修改成功！");
        }
        else{
            System.out.println("修改失败！");
        }
    }
    public static ArrayList<Integer> checkId(int date,String name){

        return (getAllData.getOneData(date,name));
    }
    public static void deleteAll(){
        String sql="delete from timetable;";
        boolean result=setTime(sql);
        if (result){
            System.out.println("删除成功！");
        }
        else{
            System.out.println("删除失败！");
        }
    }
}
